<?php
require_once("../lib/func.autoloader.php");
// crud.php
// CRUD (Create, Read, Update, Delete) management page.
// Copyright 2007, Alex McClung

// ===============================================================================
// DEFINES
define('MODE_ADD',    'add');
define('MODE_EDIT',   'edit');
define('MODE_REMOVE', 'remove');
define('MODE_PORTAL', 'portal');

// Reserve strings
$tpl          = ""; // Template file to display
$title        = ""; // Page title
$func         = ""; // Function to perform on the DBO (Insert, Update, or Remove)
$message_ok   = ""; // Success message
$message_fail = ""; // Failure message

// ===============================================================================
// INIT

// If the user is not logged in, redirect them to the login page
$sc = new SuperConstructor();
if(false === $sc->getUser()) { header("Location: {$sc->config->LoginPage}"); exit(); }

// Get mode (from GET) (default to portal mode)
$mode = $_GET['mode'];

// Load the binding. It tells us the table we're operating on, its (english) name, and the form we should use
// The ID should ALWAYS be in $_GET!
$binding = new SC_Binding($_GET['i']);

// Create the row instance for this binding's table
$row = SimpleDBOFactory::Create($binding->table);

// If the ID is set in GET (like when we're in edit or remove mode), initialize
// the object with it.
if(isset($_GET['r']))
	$row->Get($_GET['r']);

// If POST is set, load POST data into the object
if(count($_POST) > 0)
{
	// Go ahead and get all of the data in there that we can
	$sc->LoadFormData($_POST, $row);
	
	// If we're REMOVING the guy, refresh his data (because all of the form inputs will be disabled,
	// and therefore won't be in POST data)
	if($mode == MODE_REMOVE && count($_POST) > 0)
		$row->Get($row->{$row->_dbo_id_column});
}
	
// ===============================================================================
// MAIN EXECUTION

// Figure out things based on which mode we're in
switch($mode)
{
	case MODE_ADD:
			$tpl          = "add.tpl";
			$title        = "{$binding->name} (Add)";
			$func         = "Insert";
			$message_ok   = "Add successful.";
			$message_fail = "Add failed.";
		break;
	
	case MODE_EDIT:
			$tpl          = "edit.tpl";
			$title        = "{$binding->name} (Edit)";
			$func         = "Update";
			$message_ok   = "Edit successful.";
			$message_fail = "Edit failed.";
		break;
	
	case MODE_REMOVE:
			$tpl          = "remove.tpl";
			$title        = "{$binding->name} (Remove)";
			$func         = "Remove";
			$message_ok   = "Remove successful.";
			$message_fail = "Remove failed.";
		break;
	
	case MODE_PORTAL:
	default:
			$mode  = MODE_PORTAL; // Make sure mode is initialized with a value
			$tpl   = "index.tpl";
			$title = $binding->name;
		break;
}

// Assign common template variables (it is important to do this before the next step)
$sc->assign("pageTitle",      $title );
$sc->assign("mode",           $mode  );
$sc->assign_by_ref("row",     $row   );
$sc->assign_by_ref("binding", $binding   );

// Is there an operation to perform on our little object?
if(strlen($func) > 0 && count($_POST) > 0 && $mode != MODE_PORTAL)
{
	// If there are no error messages, we can try and update the database
	if( MQ::NumMessages(MQ_ERROR) == 0 )
	{
		// Try and do something
		if($row->$func())
		{
			// Tell them how awesome they are
			MQ::OK($message_ok);
			
			// Clear form data ONLY if we're in add mode
			if($mode == MODE_ADD)
			{
				$sc->clear_assign("row");
			}
			// And if we're in remove mode, make sure we don't show the submit button again
			else if($mode == MODE_REMOVE)
			{
				// Actually, show the portal page
				$tpl = "index.tpl";
				$mode = MODE_PORTAL;
			}
		}
		else
		{
			// Tell them how badly they failed.
			MQ::Error($message_fail);
			MQ::Error($row->LastError());
		}
	}
}

// Are we in portal mode? (this is not an else if on PURPOSE!)
if($mode == MODE_PORTAL)
{
	// Load the existing rows
	$row    = SimpleDBOFactory::Create($binding->table);
	$search = new SimpleDBOSearch($row);
	$result = $search->Search();
	$rows   = $result->All($row);
	
	// Load the first N columns
	$allcols = $row->GetColumnNames();
	$cols = array();
	for($i=0; $i<5; $i++)	// TODO: Put '5' into a constant (or the config file!?)
	{
		if(isset($allcols[$i]))
			$cols[$i] = $allcols[$i];
	}
	
	// Cleanup
	unset($result, $search, $allcols);
	
	// Assign template variables
	$sc->assign_by_ref("rows", $rows);
	$sc->assign_by_ref("cols", $cols);
}

// Cleanup
unset($title, $func, $message_ok, $message_fail);

// TEMPLATE! DISPLAY!
$sc->display("admin/pages/CRUD/$tpl");
?>